﻿#include "salemodel.h"
#include <QDebug>
#include "user.h"
#include "tools.h"

SaleModel::SaleModel(QObject *parent) : QStandardItemModel(parent)
{
    header<<"商品型号"
         <<"商品名称"
        <<"单位"
       <<"库存"
      <<"数量"
     <<"单价"
    <<"金额"
    <<"货号"
    <<"条形码";

    setHorizontalHeaderLabels(header);
    connect(&importThread, &ExcelImportThread::importDataDone,
            [=](QList<QList<QVariant>> data)
    {
        SaleModel::updateData(data);
        importThread.quit();
        importThread.wait();
    });

    connect(&exportThread, &ExcelExportThread::exportDataDone,
            [=]()
    {
        qDebug()<<"导出数据成功";
        emit SaleModel::exportDataDone();
        exportThread.quit();
        exportThread.wait();
    });
}

bool SaleModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (index.column() != 4 && index.column() != 5)
    {
        return false;
    }

    int count = 0;
    double price = 0;
    if(index.column()==4)
    {
        count = value.toInt();
        price = item(index.row(), 5)->text().toDouble();
        price = QString::number(price, 'f', 2).toDouble();
        if(count<0)count=0;
        QStandardItemModel::setData(index, count, role);
    }else{
        count = item(index.row(), 4)->text().toInt();
        price = value.toDouble();
        price = QString::number(price, 'f', 2).toDouble();
        if(price<0)price=0;
        QStandardItemModel::setData(index, price, role);
    }

    DingdanDetail *dingdanDetail = dingdanDetails[index.row()];
    dingdanDetail->count = count;
    dingdanDetail->price = price;

    double totalMoney = price * count;
    QStandardItemModel::setItem(index.row(), 6, new QStandardItem(QString::number(totalMoney, 'f', 2)));
    refresh();
    return true;
}

QVariant SaleModel::data(const QModelIndex &index, int role) const
{
    QVariant value = QStandardItemModel::data(index, role);
    //设置内容居中
    if(role==Qt::TextAlignmentRole){
        return  Qt::AlignCenter;
    }

    //设置内容颜色
    if (role == Qt::TextColorRole && (index.column() == 4 || index.column()==5))
        return QVariant::fromValue(QColor(Qt::blue));
    return value;
}

void SaleModel::setWidgetType(UserRelation::RelationType widgetType){
    this->widgetType = widgetType;
}

void SaleModel::insertProduct(int insertRowIndex, Product &product, int defaultCount){
    DingdanDetail *dingdanDetail = new DingdanDetail();

    dingdanDetail->username = User::getUsername();
    dingdanDetail->productId = product.productId;
    dingdanDetail->count = defaultCount;
    dingdanDetail->price = 0;

    QList<QStandardItem*> rowData;
    rowData.append(new QStandardItem(product.type));
    rowData.append(new QStandardItem(product.name));
    rowData.append(new QStandardItem(product.unit));
    rowData.append(new QStandardItem(QString("%1").arg(product.count)));
    rowData.append(new QStandardItem(QString("%1").arg(defaultCount)));
    rowData.append(new QStandardItem("0.00"));
    rowData.append(new QStandardItem(QString("0.00")));
    rowData.append(new QStandardItem(product.productNum));
    rowData.append(new QStandardItem(product.barCode));

    products.append(&product);
    dingdanDetails.insert(insertRowIndex, dingdanDetail);
    insertRow(insertRowIndex, rowData);
}

void SaleModel::insertProduct(int startIndex, QList<Product*> insertProducts, int defaultCount){
    int i=0;
    for(Product *product:insertProducts){
        if(product->checkExists(products)){
            i++;
        }else{
            insertProduct(startIndex, *product, defaultCount);
            startIndex += 1;
        }
    }

    if(i != 0){
        Tools::showRepeatProductMsg();
    }

    refresh();
}

void SaleModel::insertDingdanDetail(DingdanDetail &detail){
    Product *product = detail.getProduct();

    detail.count = detail.count>0?detail.count:detail.count*-1;

    QList<QStandardItem*> rowData;
    rowData.append(new QStandardItem(product==nullptr?"":product->type));
    rowData.append(new QStandardItem(product==nullptr?"":product->name));
    rowData.append(new QStandardItem(product==nullptr?"":product->unit));
    rowData.append(new QStandardItem(product==nullptr?"":QString("%1").arg(product->count)));
    rowData.append(new QStandardItem(QString("%1").arg(detail.count)));
    rowData.append(new QStandardItem(QString::number(detail.price, 'f', 2)));
    rowData.append(new QStandardItem(QString::number(detail.count*detail.price, 'f', 2)));
    rowData.append(new QStandardItem(product==nullptr?"":product->productNum));
    rowData.append(new QStandardItem(product==nullptr?"":product->barCode));

    products.append(product);
    dingdanDetails.append(&detail);
    insertRow(rowCount()-1, rowData);
}

void SaleModel::insertDingdanDetail(QList<DingdanDetail*> details){
    for(DingdanDetail *detail:details){
        insertDingdanDetail(*detail);
    }

    refresh();
}

void SaleModel::updateProductPrice(QList<HistoryProduct*> historyProducts){
    for(int i=0;i<historyProducts.size();i++){
        DingdanDetail *detail = dingdanDetails[i];
        detail->price = historyProducts[i]->historyPrice;
        setItem(i, 5, new QStandardItem(QString::number(detail->price, 'f', 2)));
        setItem(i, 6, new QStandardItem(QString::number(detail->price*detail->count, 'f', 2)));
    }
}

void SaleModel::removeRowData(int row){
    dingdanDetails.removeAt(row);
    products.removeAt(row);
    removeRow(row);
}

void SaleModel::refresh(){
    int totalCount = 0;
    double totalMoney = 0;

    for(int i=0; i< rowCount()-1;i++){
        int count = item(i, 4)->text().toInt();
        double price = item(i, 5)->text().toDouble();
        totalCount += count;
        totalMoney += count * price;
    }

    //qDebug()<<totalCount<<totalMoney;

    emit updateTotal(totalCount, totalMoney);
}

void SaleModel::reset(){
    clear();
    products.clear();
    dingdanDetails.clear();
    setHorizontalHeaderLabels(header);

    refresh();
}

QList<DingdanDetail*> SaleModel::currentDingdanDetails(){
    return dingdanDetails;
}

void SaleModel::updateData(QList<QList<QVariant>> data)
{
    clear();
    QList<QVariant> header = data.at(0);

    int col = header.size();
    for(int i=0; i<col; i++)
    {
        setHorizontalHeaderItem(i, new QStandardItem(header.at(i).toString()));
    }

    for(int i=1; i<data.size();i++){
        for(int j=0;j<col;j++){
            setItem(i-1,j,new QStandardItem(data.at(i).at(j).toString()));
        }
    }

    refresh();
    emit importDataDone();
}

QList<QList<QVariant>> SaleModel::getExportData()
{
    QList<QList<QVariant>> data;

    QList<QVariant> headers;
    for(int i=0;i<columnCount();i++){
        headers.append(horizontalHeaderItem(i)->text());
    }
    data.append(headers);

    for(int i=0;i<rowCount();++i)
    {
        QList<QVariant> rows;
        for(int j=0;j<columnCount() ;++j)
        {
            rows.append(item(i,j)->text());
        }
        data.append(rows);
    }

    return data;
}

void SaleModel::importDataFromExcel(QString fileName)
{
    importThread.setFileName(fileName);
    importThread.start();
}

void SaleModel::exportDataToExcel(QString fileName)
{
    exportThread.setFileName(fileName);
    exportThread.setExportData(getExportData());
    exportThread.start();
}
